package com.wuyou.sso.component;

import com.wuyou.sso.common.entity.User;
import com.wuyou.sso.common.userDetails.CustomizedUser;
import com.wuyou.sso.domain.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * CustomizedUserDetailsServiceImpl
 *
 * @Date 2025/4/24 14:40
 * @Author 无忧
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CustomizedUserDetailsServiceImpl implements UserDetailsService {

    private final LoginFactory loginFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserVO userVO = loginFactory.handle(username);
        if (userVO == null) {
            // 不管什么原因查询不到对应值，从安全角度而言都先欺骗一下调用方用户名或密码错误
            throw new BadCredentialsException("用户名或密码错误");
        }
        if (userVO.getUserInfo() == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        User user = userVO.getUserInfo();
        CustomizedUser userDetails = new CustomizedUser(user.getId(), user.getDeptId(), user.getUsername(), user.getPassword(), user.getMobile(),
                                                true, true, true, true, Collections.emptyList(), user.getDisplayName(), Collections.emptyList());
        userDetails.setTenantId(1L);

        return userDetails;
    }
}
